//
//  XMRechargeViewController.m
//  XunMi
//
//  Created by MacBook on 2024/2/29.
//  Copyright © 2024 TieZhu. All rights reserved.
//

#import "XMRechargeViewController.h"
#import "XMRechargeListViewController.h"
#import "XMRechargeCollectionViewCell.h"
#import "XMMemberViewController.h"
#import "XMRechargeModel.h"
#import "XMDiscountsModel.h"
#import "XMDiscountListViewController.h"
#import "YHIAPManager.h"

@interface XMRechargeViewController ()<UICollectionViewDelegate, UICollectionViewDataSource>

@property (weak, nonatomic) IBOutlet UIImageView *topBgImgV;
@property (weak, nonatomic) IBOutlet UILabel *memberTipLa;
@property (weak, nonatomic) IBOutlet UILabel *remarkLa;
@property (weak, nonatomic) IBOutlet UILabel *discountLa;
@property (weak, nonatomic) IBOutlet UIButton *balanceBtn;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UIButton *appleBtn;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *space;
@property (weak, nonatomic) IBOutlet UIView *discountsView;
@property (weak, nonatomic) IBOutlet UIImageView *disTipImgV;

@property (weak, nonatomic) IBOutlet UIButton *agreeBtn;
@property (nonatomic, assign) NSInteger coupon;

@property (nonatomic, strong) NSArray <XMRechargeModel *> *dataArray;
@property (nonatomic, strong) NSArray <XMDiscountsModel *> *usableArray;
@property (nonatomic, strong) NSArray <XMDiscountsModel *> *invalidArray;
@property (nonatomic, strong) XMDiscountsModel *discountsModel;
@end

@implementation XMRechargeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.coupon = 0;
    [self setupSubviews];
    [self mineUserInfo];
    [self rechargeList];
}

- (void)mineUserInfo {
    NSMutableDictionary *dic = @{
        @"module": @"4"
    }.mutableCopy;
    [YHNetworkManager.sharedInstance postWithUrl:@"api/user/obtain" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
        if (tip.success) {
            XMUserModel *model = [XMUserModel mj_objectWithKeyValues:result];
            if ([XMUtil isBlankString:model.member_time]) {
                self.topBgImgV.image = kGetImage(@"member_0");
                self.memberTipLa.text = @"您还不是会员，会员权益更多";
                self.memberTipLa.textColor = k1F1F1F;
            } else {
                self.topBgImgV.image = kGetImage(@"member_1");
                self.memberTipLa.text = model.member_time;
                self.memberTipLa.textColor = kHEX(@"#FBCF8E");
            }
            
            [self.balanceBtn setTitle:kValueToString(model.golds) forState:UIControlStateNormal];
        }
    }];
}

//- (void)getUserBalance {
//    NSMutableDictionary *dic = @{
//        @"module": @"3"
//    }.mutableCopy;
//    [YHNetworkManager.sharedInstance postWithUrl:@"api/user/obtain" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
//        if (tip.success) {
//            XMUserModel *model = [XMUserModel mj_objectWithKeyValues:result];
//            if ([XMUtil isBlankString:model.member_time]) {
//                self.topBgImgV.image = kGetImage(@"member_0");
//                self.memberTipLa.text = @"您还不是会员，会员权益更多";
//                self.memberTipLa.textColor = k1F1F1F;
//            } else {
//                self.topBgImgV.image = kGetImage(@"member_1");
//                self.memberTipLa.text = model.member_time;
//                self.memberTipLa.textColor = kHEX(@"#FBCF8E");
//            }
//            
//            [self.balanceBtn setTitle:kValueToString(model.golds) forState:UIControlStateNormal];
//        }
//    }];
//}

- (void)rechargeList {
    [MBProgressHUD showHUDActivityMsg:nil toView:kWindow];
    NSMutableDictionary *dic = @{}.mutableCopy;
    
    [YHNetworkManager.sharedInstance postWithUrl:@"api/config/rechargeList" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
        if (tip.success) {
            [MBProgressHUD hideHUD];
            NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
            paragraphStyle.lineSpacing = 8; // 设置行高为 10 points
            // 创建一个 NSAttributedString 对象，将上述样式应用到文本中
            NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:[result toString:@"remarks"] attributes:@{NSParagraphStyleAttributeName: paragraphStyle}];
            self.remarkLa.attributedText = attributedString;
            [self.remarkLa sizeToFit]; // 自适应文本内容的大小
            
            self.dataArray = [XMRechargeModel mj_objectArrayWithKeyValuesArray:result[@"record"]];
            [self.collectionView reloadData];
            self.dataArray.firstObject.selected = YES;
            [self discountsListAmount:self.dataArray.firstObject.money];
        }
    }];
}

- (void)discountsListAmount:(NSString *)amount {
    NSMutableDictionary *dic = @{
        @"amount": kValueToString(amount)
    }.mutableCopy;
    
    [YHNetworkManager.sharedInstance postWithUrl:@"api/money/paymentCard" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
        if (tip.success) {
            NSArray *usable = result[@"usable"];
            NSArray *invalid = result[@"invalid"];
            if (usable.count == 0) {
                self.discountsView.hidden = YES;
                self.space.constant = 16;
            } else {
                self.discountsView.hidden = NO;
                self.space.constant = 80;
                self.usableArray = [XMDiscountsModel mj_objectArrayWithKeyValuesArray:usable];
                self.discountLa.text = @"选择优惠卡卷";
                self.disTipImgV.hidden = YES;
                self.discountsModel = nil;
            }
            
            if (invalid.count > 0) {
                self.invalidArray = [XMDiscountsModel mj_objectArrayWithKeyValuesArray:invalid];
            }
        }
    }];
}

#pragma mark - setupSubviews
- (void)setupSubviews {
    [self.navLeft2Btn setTitle:@"金币充值" forState:UIControlStateNormal];
    
    [self.navRightBtn setImage:kGetImage(@"re_r") forState:UIControlStateNormal];
    [self.navRightBtn addTarget:self action:@selector(reList) forControlEvents:UIControlEventTouchUpInside];
    
    [self.balanceBtn setImagePosition:(XMImagePositionLeft) spacing:4];
    [self.appleBtn setImagePosition:(XMImagePositionLeft) spacing:12];
    
    kCornerRadius(_appleBtn, 6, 1, UIColor.blackColor);
    
    kCornerRadius(_discountsView, 10, 0, UIColor.clearColor);
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(98, 108);
    layout.minimumLineSpacing = 14;
    layout.minimumInteritemSpacing = 14;
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    [self.collectionView setCollectionViewLayout:layout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerNib:kNibWithName(kStringFromClass(XMRechargeCollectionViewCell)) forCellWithReuseIdentifier:kStringFromClass(XMRechargeCollectionViewCell)];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toMember)];
    [self.topBgImgV addGestureRecognizer:tap];
}

- (void)reList {
    XMRechargeListViewController *vc = [[XMRechargeListViewController alloc] init];
    [self.navigationController pushViewController:vc
                                         animated:YES];
}

- (IBAction)rechargeAct:(UIButton *)sender {
    if (!self.agreeBtn.selected) {
        [MBProgressHUD showHUDMsg:@"请先阅读并同意充值协议" toView:nil];
        return;
    }
    
    XMRechargeModel *model;

    for (XMRechargeModel *tModel in self.dataArray) {
        if (tModel.selected) {
            model = tModel;
            break;
        }
    }
    
    if (![NSString isEmpty:model.product_id]) {
        [[YHNetworkManager sharedInstance] postWithUrl:@"api/money/prepareOrder" parameters:@{@"index": model.index, @"type": @(1), @"coupon": @(self.coupon), @"method": @"appstore"}.mutableCopy completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
            if (tip.success) {
                NSString *orderId = [result toString:@"order_sn"];
                [self applePayWith:model.product_id orderId:orderId];
            }

        }];
    }
    
}

- (void)applePayWith:(NSString *)productId orderId:(NSString *)orderId {
    [MBProgressHUD showHUDActivityMsg:nil];
    XMWeakSelf(self);
    [[YHIAPManager sharedInstance] startPurchaseWithProductId:productId
                                                      orderId:orderId
                                               completeHandle:^(YHIAPPurchType type, NSData *_Nonnull data) {
        XMStrongSelf(self);
        [MBProgressHUD hideHUD];
        if (type == IAPPurchFailed) {
            [MBProgressHUD showHUDMsg:@"充值失败" toView:nil];
        }
        if (type == IAPPurchCancel) {
            [MBProgressHUD showHUDMsg:@"取消充值" toView:nil];
        }
        
        if (type == IAPPurchVerSuccess) {
            [MBProgressHUD showHUDMsg:@"充值成功" toView:nil];
            [self mineUserInfo];
        }
        
    }];
}

- (IBAction)selAct:(UIButton *)sender {
    sender.selected = !sender.selected;
}

- (IBAction)xieyiAct:(UIButton *)sender {
    XMWebViewController *vc = [[XMWebViewController alloc] init];
    vc.title = @"充值协议";
    vc.urlStr = kGlobalVariables.appConfig.privacy.rechargeAgreement;
    vc.needNav = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)discounts:(UIButton *)sender {
    XMDiscountListViewController *vc = [[XMDiscountListViewController alloc] init];
    [vc setDataUsableArray:self.usableArray invalidArray:self.invalidArray];
    [self.navigationController pushViewController:vc animated:YES];
    
    XMWeakSelf(self);
    vc.selBlock = ^(XMDiscountsModel * _Nonnull model) {
        XMStrongSelf(self);
        self.discountsModel = model;
        if (model != nil) {
            self.discountLa.text = kStringFormat(@"-¥%@", model.reduce);
            self.disTipImgV.hidden = NO;
            [self.usableArray enumerateObjectsUsingBlock:^(XMDiscountsModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if (obj.index.intValue == model.index.intValue) {
                    obj.selected = YES;
                    self.coupon = obj.index.intValue;
                    *stop = YES;
                    return;
                }
            }];
        } else {
            self.discountLa.text = @"选择优惠卡卷";
            self.disTipImgV.hidden = YES;
            [self.usableArray enumerateObjectsUsingBlock:^(XMDiscountsModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                obj.selected = NO;
                self.coupon = 0;
            }];
        }
    };
}

- (void)toMember {
    XMMemberViewController *vc = [[XMMemberViewController alloc] initWithNibName:kStringFromClass(XMMemberViewController) bundle:nil];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - UICollectionViewDelegate

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    XMRechargeCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kStringFromClass(XMRechargeCollectionViewCell) forIndexPath:indexPath];
    cell.model = [self.dataArray safe_objectAtIndex:indexPath.item];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [self.dataArray enumerateObjectsUsingBlock:^(XMRechargeModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (indexPath.item == idx) {
            obj.selected = YES;
        } else {
            obj.selected = NO;
        }
    }];
    [self.collectionView reloadData];
    XMRechargeModel *model = self.dataArray[indexPath.item];
    [self discountsListAmount:model.money];
}

@end
